package com.hyh.eblog.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hyh.eblog.entity.Post;
import com.hyh.eblog.mapper.PostMapper;
import com.hyh.eblog.service.PostService;
import com.hyh.eblog.util.RedisUtil;
import com.hyh.eblog.vo.CollectionVo;
import com.hyh.eblog.vo.PostVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Summerday
 * @since 2020-10-19
 */
@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements PostService {

    @Resource
    PostMapper postMapper;

    @Resource
    RedisUtil redisUtil;

    @Override
    public IPage<PostVo> paging(Page page, Long categoryId, Long userId, Integer level, Boolean recommend, String order) {
        if (level == null) level = -1;
        QueryWrapper wrapper = new QueryWrapper<Post>()
                .eq(categoryId != null, "category_id", categoryId)
                .eq(userId != null, "user_id", userId)
                .eq(level == 0, "level", 0)
                .gt(level > 0, "level", 0)
                .orderByDesc(order != null, order);
        return postMapper.selectPosts(page, wrapper);
    }

    @Override
    public PostVo selectOnePost(QueryWrapper<Post> wrapper) {

        return postMapper.selectOnePost(wrapper);
    }

    /**
     * 本周热议
     */
    @Override
    public void initWeekRank() {

        // 获取七天内发表的文章
        List<Post> posts = this.list(new QueryWrapper<Post>()
                .ge("created", DateUtil.offsetDay(new Date(), -7))
                .select("id,title,user_id,comment_count,view_count,created"));
        // 初始化文章的总阅读量
        for (Post post : posts) {
            String key = "day:rank:" + DateUtil.format(post.getCreated(), DatePattern.PURE_DATE_FORMAT);
            // zadd day:rank:20201018 10 1
            redisUtil.zSet(key, post.getId(), post.getCommentCount());

            // 7天后自动过期
            long between = DateUtil.between(new Date(), post.getCreated(), DateUnit.DAY);
            long expireTime = (7 - between) * 24 * 60 * 60;
            // expire day:rank:20201018 xxx
            redisUtil.expire(key, expireTime);
            //缓存文章的一些基本信息[id, 标题, 评论数量, 作者id]
            this.hashCachePostIdAndTitle(post, expireTime);

        }
        // 并集
        this.zUnionAndStoreLast7DayForWeekRank();
    }

    @Override
    public void incrCommentCountAndUnionForWeekRank(long postId, boolean isIncr) {
        // 获取当前日期
        String currentKey = "day:rank:" + DateUtil.format(new Date(), DatePattern.PURE_DATE_FORMAT);
        // +1 -1 ?
        redisUtil.zIncrementScore(currentKey, postId, isIncr ? 1 : -1);

        Post post = this.getById(postId);
        // 7天后自动过期
        long between = DateUtil.between(new Date(), post.getCreated(), DateUnit.DAY);
        long expireTime = (7 - between) * 24 * 60 * 60;

        // 缓存文章的基本信息
        this.hashCachePostIdAndTitle(post, expireTime);

        // 并集
        this.zUnionAndStoreLast7DayForWeekRank();
    }

    @Override
    public void setViewCount(PostVo postVo) {
        String key = "rank:post:" + postVo.getId();
        // 缓存中获取view count
        Integer viewCount = (Integer) redisUtil.hget(key, "post:viewCount");
        // +1
        if(viewCount != null){
            postVo.setViewCount(viewCount + 1);
        }else{
            postVo.setViewCount(postVo.getViewCount() + 1);
        }
        // 更新缓存
        redisUtil.hset(key,"post:viewCount",postVo.getViewCount());
    }

    @Override
    public IPage<CollectionVo> paging(Page page, Long userId) {

        return postMapper.selectCollection(page,userId);
    }


    /**
     * 本周合并每日评论数量统计
     */
    private void zUnionAndStoreLast7DayForWeekRank() {
        String currentKey = "day:rank:" + DateUtil.format(new Date(), DatePattern.PURE_DATE_FORMAT);
        String destKey = "week:rank";
        List<String> otherKeys = new ArrayList<>();
        for (int i = -6; i < 0; i++) {
            String temp = "day:rank:" + DateUtil.format(DateUtil.offsetDay(new Date(), i), DatePattern.PURE_DATE_FORMAT);
            otherKeys.add(temp);
        }
        redisUtil.zUnionAndStore(currentKey, otherKeys, destKey);
    }

    /**
     * 缓存文章的一些基本信息[id, 标题, 评论数量, 作者id]
     *
     * @param post       文章
     * @param expireTime 过期时间
     */
    private void hashCachePostIdAndTitle(Post post, long expireTime) {
        String key = "rank:post:" + post.getId();
        if (!redisUtil.hasKey(key)) {
            redisUtil.hset(key, "post:id", post.getId(), expireTime);
            redisUtil.hset(key, "post:title", post.getTitle(), expireTime);
            redisUtil.hset(key, "post:commentCount", post.getCommentCount(), expireTime);
            redisUtil.hset(key, "post:viewCount", post.getViewCount(), expireTime);
        }
    }
}
